package org.jeecg.modules.salary.service.impl;

import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.modules.salary.entity.SalaryFields;
import org.jeecg.modules.salary.entity.SysSalary;
import org.jeecg.modules.salary.mapper.SalarySubMapper;
import org.jeecg.modules.salary.service.ISalaryAdjustService;
import org.jeecg.modules.salary.service.ISalaryFieldsService;
import org.jeecg.modules.salary.service.ISalarySubService;
import org.jeecg.modules.salary.service.ISysSalaryService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

/**
 * <B>系统名称：</B><BR>
 * <B>模块名称：</B><BR>
 * <B>中文类名：</B><BR>
 * <B>概要说明：</B><BR>
 *
 * @author 中科软科技
 * @since 2020/8/19
 */
@Slf4j
@Service
public class SalarySubServiceImpl implements ISalarySubService {

    @Autowired
    SalarySubMapper salarySubMapper;

    @Autowired
    private ISalaryAdjustService salaryAdjustService;

    @Autowired
    ISysSalaryService sysSalaryService;

    @Autowired
    ISalaryFieldsService salaryFieldsService;


    @Override
    public boolean insertField(String fieldName) {
        return salarySubMapper.insertFields(fieldName)>0?true:false;
    }

    @Override
    public boolean deleteField(String fieldName) {
        return salarySubMapper.deleteFields(fieldName)>0?true:false;
    }

    @Override
    public boolean updateSalarySub(Map map) {

        return salarySubMapper.updateSalarySub(map)>0?true:false;
    }

    @Override
    public boolean insertSalarySub(Map map) {
        return salarySubMapper.insertSalarySub(map)>0?true:false;
    }

    @Override
    public Map getById(String id) {
        return salarySubMapper.getById(id);
    }

    @Override
    public List getAll() {
        return salarySubMapper.getAll();
    }

    @Override
    public List<SalaryFields> getCalculation(Map<String,String> map) {

        List<SalaryFields>  salaryFieldsList = new ArrayList<>();
        Map<String,Object> map1 = new HashMap();
        Map<String,String> resultMap = new HashMap<>();
        Map<String,String> gsMap = new HashMap();
        String fieldSource = "";
        for (String key : map.keySet()){
            LambdaQueryWrapper<SalaryFields> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(SalaryFields::getFieldCode,key);
            SalaryFields salaryFields = salaryFieldsService.getOne(queryWrapper);
            salaryFields.setFieldDefault(map.get(key));
            if(CommonConstant.STATUS_1.equals(salaryFields.getFieldDefaultSet())){
                map1.put(salaryFields.getFieldCode(),new BigDecimal(map.get(key)));
            }else{
                gsMap.put(salaryFields.getFieldCode(),salaryFields.getFieldSource());
            }
            salaryFieldsList.add(salaryFields);
        }
        //遍历
        for(String key:gsMap.keySet()){
            String value = gsMap.get(key);
            String result = getResult(value,map1);
            resultMap.put(key,result);
        }
        for(SalaryFields salaryFields:salaryFieldsList){
            for(String key:resultMap.keySet()){
                String value = resultMap.get(key);
                if(key.equals(salaryFields.getFieldCode())){
                    salaryFields.setFieldDefault(value);
                    break;
                }
            }
        }
        return salaryFieldsList;
    }

    @Override
    public List<SalaryFields> getSubInfo(String userId, String reportId) {
        Map<String,String>  map = new HashMap();
        //查询是否已经上报
        SysSalary salary = sysSalaryService.getByUserId(userId,reportId);
        List<SalaryFields> list = salaryFieldsService.list();
        if(Objects.nonNull(salary)){
            //查询录入数据
            map = getById(salary.getId());
            for (SalaryFields field : list){
                String code = field.getFieldCode();
                String value = map.get(code);
                if(Double.valueOf(value) != 0){
                    field.setIsReport("isReport");
                    field.setFieldDefault(map.get(code));
                }else{
                    //查询薪资是否已调整
                    String max = salaryAdjustService.getMaxMoney(userId,field.getId());
                    if(StringUtils.isNotEmpty(max)){
                        //插入已调整后的薪资
                        field.setFieldDefault(max);
                    }
                }
            }
        }else{
            for (SalaryFields field : list){
                //查询薪资是否已调整
                String max = salaryAdjustService.getMaxMoney(userId,field.getId());
                if(StringUtils.isNotEmpty(max)){
                    //插入已调整后的薪资
                    field.setFieldDefault(max);
                }
            }
        }

        //对获计算值进行计算
        Map<String,Object> map1 = new HashMap();
        Map<String,String> resultMap = new HashMap<>();
        Map<String,String> gsMap = new HashMap();
        for(SalaryFields salaryFields : list){
            if(CommonConstant.STATUS_1.equals(salaryFields.getFieldDefaultSet())){
                map1.put(salaryFields.getFieldCode(),new BigDecimal(salaryFields.getFieldDefault()));
            }else{
                gsMap.put(salaryFields.getFieldCode(),salaryFields.getFieldSource());
            }
        }


        //遍历
        for(String key:gsMap.keySet()){
            String value = gsMap.get(key);
            String result = getResult(value,map1);
            resultMap.put(key,result);
        }


        for(SalaryFields fields : list){
            for(String key:resultMap.keySet()){
                String value = resultMap.get(key);
                if(key.equals(fields.getFieldCode())){
                    fields.setFieldDefault(value);
                    break;
                }
            }
        }


        return list;
    }


    /**
     * 处理公式计算方法
     * @param fieldSource
     * @param map
     * @return
     */
    public String getResult(String fieldSource, Map map){
        String result = "";
        try{
            Document doc = Jsoup.parse(fieldSource);
            Elements elements = doc.select("span");
            StringBuffer sb = new StringBuffer();
            sb.append("${");
            for (Element element:elements) {
                //获取class属性
                String cssClass = element.attr("class");
                if (cssClass.contains("charachter")) {
                    sb.append(element.attr("id"));
                }else if(cssClass.contains("number-operator")){
                    sb.append(element.text());
                }
            }
            sb.append("}");
            TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig());
            Template template = engine.getTemplate(sb.toString());
            result = template.render(map);
            //去除数字中千位符,
            result = result.replace( ",", "") ;

        }catch (Exception e){
            log.error(e.getMessage());
            result = "公式错误";
        }
        return result;
    }
}
